/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../stores/definitions_set';

const FromItem = Form.Item;

const ShiftTimeForm = ({
  visible,
  modal,
  onSubmit,
  onCancel,
  shiftsInfo,
}) => {
  // eslint-disable-next-line no-unused-vars
  const { scShareStore: store } = useStore();
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [share] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    _.assign(share, shiftsInfo);
    editCtx.origin = _.cloneDeep({});
    // 添加操作,设置默认值
    return () => {
      _.assign(share, {
        payEndTime: '',
        notGroupPayEndTime: '',
      });
    };
  }, [visible]);

  if (!share) return <></>;

  const overrideModel = {
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(share, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(share);
  };

  return (
    <>
      <Dialog
        visible={!!visible}
        onCancel={handleCancel}
        onClose={handleCancel}
        title={t`编辑下单截止时间`}
        style={{ width: '30%' }}
        footer={null}
      >
        <Form
          isPreview={isViewMode}
          {...formProps}
          value={share}
          colon
          onChange={handleChange}
          useLabelForErrorMessage
        >
          <FieldsGrid
            formData={share}
            mode={modal[0]}
            columns={1}
            overrideModel={overrideModel}
            fields={['payEndTime', 'notGroupPayEndTime']}
          />
          <DrawerFooter>
            <FromItem>
              {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
              <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
            </FromItem>
          </DrawerFooter>
        </Form>
      </Dialog>
    </>
  );
};

export default observer(ShiftTimeForm);
